// 定义类型别名来描述用户信息的结构
/**
 *
 *
 * @property {string} username - 用户名
 * @property {string} password - 密码
 */
import { ElMessage } from 'element-plus'
import store from './../store'
import IndexedDBManager from './../db/db'
import { ethers } from 'ethers'

async function ObtainJWT() {
  const dbName = 'dexcpro';
  const storeName = 'user';
  let dexcuser = new IndexedDBManager(dbName, storeName);
  let JWT = await dexcuser.getObject(1)
  if (JWT) {
    return JWT.JWT
  } else {
    return '';
  }
}

async function dataRequest(controller, method, data) {
  try {
    let JWT = await ObtainJWT()
    //! https://v1.dexc.pro/项目名称/版本/控制器/方法
    //! https://v1.dexc.pro/edu/v1/api/too
    const response = await fetch(`https://v1.dexc.pro/jz/v1/${controller}/${method}`, {
      method: 'POST',
      mode: 'cors', // 设置为 cors 模式
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
        'Content-Length': JSON.stringify(data).length.toString(),
        'Authorization': JWT, // 添加包含JWT令牌的Authorization头部
      },
      body: JSON.stringify(data),
    });

    if (!response.ok) {
      throw new Error('Network response was not ok');
    }

    const returndata = await response.json();
    return returndata;
  } catch (error) {
    throw ElMessage.error('网络好像出了问题');

  }
}

async function filesRequest(data) {
  try {
    let JWT = await ObtainJWT()
    const controller = new AbortController();
    const id = setTimeout(() => controller.abort(), 30000);
    // https://api.dexc.pro/api.php?` + data[0]
    let response = await fetch(`https://v1.dexc.pro/edu/v1/api/${data[0]}`, {
      method: 'POST',
      signal: controller.signal,
      headers: {
        'Authorization': JWT, // 添加包含JWT令牌的Authorization头部
      },
      body: data[1],
    });
    const games = await response.json();
    clearTimeout(id);
    return games;
  } catch (error) {
    return { code: 408, data: error, massage: '超时', state: 'error' };
  }
}



function setText(val) {
  if (val != null && val != "") {
    var re1 = new RegExp("<.+?>|&.+?;", "g");
    var msg = val.replace(re1, "");
    msg = msg.replace(/\s/g, "");
    msg = msg.replace(/[\r\n]/g, "");
    return msg.substr(0, 100);
  } else return '';
}
// 安装检测
async function Installationdetection() {
  // 检测是否安装是使用域名进行检测
  let array = await dataRequest('Query', 'Installation', window.location.hostname.toLowerCase().replace(/^www\./, ''));

  if (array.code == 200) {
    return true
  } else if (array.code == 503) {

  } else {
    return false
  }
}
// 自动登陆
async function automaticLogin() {
  try {
    let array = await dataRequest('Create', 'login', '');
    const dbName = 'dexcpro';
    const storeName = 'user';
    let dexcuser = new IndexedDBManager(dbName, storeName);
    let JWT = await ObtainJWT()
    if (array.code == 200) {
      if (JWT) {
        const data = { id: 1, JWT: JWT, logon: true }
        dexcuser.updateObject(data)
      }
      store.commit('setLogon', true)
      store.commit('setUser', array.data)
      return array
    } else {
      store.commit('setLogon', false)
      let JWT = await dexcuser.getObject(1)
      if (array.code == 498) {
        JWT.JWT = ''
      }
      if (JWT) {
        const data = { id: 1, JWT: JWT.JWT, logon: false }
        dexcuser.updateObject(data)
      } else {
        dexcuser.addObject({ id: 1, JWT: '', logon: false })
      }
      // ElMessage.error('登陆失败' + array.data)
      return array
    }
  } catch (error) {

  }

}
// // 检查登陆状态
// async function Loginjudgment() {
//   const dbName = 'dexcpro';
//   const storeName = 'user';
//   let dexcuser = new IndexedDBManager(dbName, storeName);
//   // 这里可能有问题
//   let arr = await dexcuser.getObject(1)

//   if (!arr.logon) {
//     ElMessage.error('请先登陆')
//     router.push({ path: '/' })
//   }
// }
// 退出登陆
async function Logoutoflogin() {
  const dbName = 'dexcpro';
  const storeName = 'user';
  let dexcuser = new IndexedDBManager(dbName, storeName);
  const data = { id: 1, JWT: '', logon: false }
  if (await dexcuser.getObject(data.id)) {
    // 存在修改
    dexcuser.updateObject(data)

  } else {
    // 不存在 添加
    dexcuser.addObject(data)

  }
  store.commit('setLogon', false)
  store.commit('setUser', null)

  setTimeout(() => {
    location.reload(true)
    ElMessage.success('退出成功')
  }, 1000);


}
// 查询代币余额
async function Checktokenbalance(address, token) {
  // 查询的前提是 已经链接了钱包
  try {
    let abi = ['function decimals() view returns (uint8)', ' function balanceOf(address account) view returns (uint256)']
    let contract = new ethers.Contract(token, abi, getprovider())
    let tx = await contract.balanceOf(address)
    let decimals = await contract.decimals()
    let balanceOf = ethers.formatUnits(tx, decimals)
    return balanceOf.toString()
  } catch (error) {
    console.error(error);
    return '0'
  }

}
// 查询ETH余额
async function Checkethbalance(address) {
  // 查询的前提是 已经链接了钱包
  try {
    let balanceOf = ethers.formatEther(
      await ethereum.request({
        method: 'eth_getBalance',
        params: [address, 'latest'],
        id: 1,
      }),
    )
    return balanceOf.toString()

  } catch (error) {
    console.error(error);
    return '0'
  }

}
// 截取小数点保留精度
function truncateDecimal(numberString, subs = 3) {
  const [integerPart, decimalPart] = numberString.split('.')
  let result = integerPart // 保留整数部分
  if (decimalPart !== undefined) {
    // 截取小数部分的前三位
    const truncatedDecimal = decimalPart.substring(0, subs)
    result += `.${truncatedDecimal}`
  }
  return result
}
// 连接钱包
async function checkNetwork() {
  let network;
  if (window.ethereum) {
    try {
      return window.ethereum.request({ method: 'eth_requestAccounts' });
    } catch (error) {

      if (error.info && error.info.error) {
        const errorMessage = error.info.error.data && error.info.error.data.message ? error.info.error.data.message : error.info.error.message

        ElMessage.error(errorMessage)
      } else {
        ElMessage.error('Error message not available')
      }
    }
  } else {
    ElMessage.error('请安装 MetaMask 或其他支持的钱包');
  }

}

// 获取签名
function getprovider() {
  let provider = null
  try {

    if (window.ethereum) {

      provider = new ethers.BrowserProvider(window.ethereum)

    } else {
      console.error('请安装 MetaMask 或其他支持的钱包');
    }

  } catch (error) {
    if (error.info && error.info.error) {
      const errorMessage = error.info.error.data && error.info.error.data.message ? error.info.error.data.message : error.info.error.message

      ElMessage.error(errorMessage)
    } else {
      ElMessage.error('Error message not available')
    }
  }
  return provider
}


export { dataRequest, filesRequest, setText, automaticLogin, Logoutoflogin, Installationdetection, checkNetwork, truncateDecimal, Checktokenbalance, getprovider, Checkethbalance };